/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wwcontrolserver;

import java.net.*;
import java.io.*;
import java.util.Date;

/**
 *
 * @author Michael Ferry
 */
public class WWControlServerMultiThread extends Thread{
    private Socket ClientSocket  = null;
    private WWControlServer WWCS;
    
    public WWControlServerMultiThread(WWControlServer control_arg,Socket socket){
        super("WWControlServerThread");
        ClientSocket = socket;
        WWCS = control_arg;
    }
    
    @Override
    public void run() {
        try {
            PrintWriter out = new PrintWriter(ClientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(ClientSocket.getInputStream()));
            String inputLine;

            System.out.println("Client Connected");

            while (!(inputLine = in.readLine()).equals("close")) {
                System.out.println(new Date() + " Client: " + inputLine);
                out.println(parseClientInput(inputLine));
            }
            out.println("close");
            out.close();
            in.close();
            ClientSocket.close();
            System.out.println("Client connection ended");
        } catch (IOException e) {
            System.out.println(e);
        }
    }
    public String parseClientInput(String input){
        String delims = "[ ]+";
        String[] tokens = input.split(delims);

        //Determine if this is a control message
        if("c".equals(tokens[0])){
            //the next two messages are for beginning and ending computer control
            //of the motor
            if("data".equals(tokens[1])){
                WWCS.SetDataCollectionStateServer(Boolean.parseBoolean(tokens[2]), Long.parseLong(tokens[3]));
            }
            //this message is used to start computer control of the motor
            else if("motor".equals(tokens[1])){
                WWCS.SetComputerMotorControlState(Boolean.parseBoolean(tokens[2]),Long.parseLong(tokens[3]),Long.parseLong(tokens[4]));
                //return WWCS.GetStatus();
            }

        }else if("s".equals(tokens[0])){
            if("gs".equals(tokens[1])){
                return WWCS.GetStatus();
            }
        }
        return WWCS.GetStatus();
    }
}
